const that = this;
export default {
  // let url = 'https://webcdn2.hsyuntai.com/files/word/%E4%B8%8A%E8%99%9E%E4%BA%BA%E6%B0%91%E5%8C%BB%E9%99%A2%E5%8C%BB%E9%99%A2%E6%B5%81%E8%A1%8C%E7%97%85%E5%AD%A6%E8%B0%83%E6%9F%A5%E8%A1%A8.docx';
  // fileLinkToStreamDownload(url, '3333表', 'docx')
  fileLinkToStreamDownload: function (url, fileName, type) {
    const xhr = new XMLHttpRequest();
    xhr.open("get", url, true);
    xhr.setRequestHeader("contentType", `application/${type}`);
    xhr.responseType = "blob";
    xhr.onload = () => {
      if (xhr.status === 200) {
        // 接受二进制文件流
        const blob = xhr.response;
        this.downloadExportFile(blob, fileName, type);
      }
    };
    xhr.send();
  },
  downloadExportFile: (blob, tagFileName, fileType) => {
    const downloadElement = document.createElement("a");
    let href = blob;
    if (typeof blob === "string") {
      downloadElement.target = "_blank";
    } else {
      href = window.URL.createObjectURL(blob); // 创建下载的链接
    }

    downloadElement.href = href;
    downloadElement.download = tagFileName; // 下载后文件名
    const event = new MouseEvent("click"); // 创建一个单击事件
    downloadElement.dispatchEvent(event); // 触发a的单击事件
    if (typeof blob !== "string") {
      window.URL.revokeObjectURL(href); // 释放掉blob对象
    }
  },

  /**
   *
   * @param name 文件名 1.docx
   * @param href 下载地址
   */
  onDownload: (name, href) => {
    const aDom = document.createElement("a");
    aDom.href = href;
    aDom.download = name;
    aDom.click();
  },

  isElement: (obj) => {
    return typeof HTMLElement === "object"
      ? obj instanceof HTMLElement
      : !!(
          obj &&
          typeof obj === "object" &&
          (obj.nodeType === 1 || obj.nodeType === 9) &&
          typeof obj.nodeName === "string"
        );
  },

  /**
   * 隐藏所有指定元素
   * @param el
   * @example hide(document.querySelectorAll("img"));  // 隐藏页面上所有<img />元素
   */
  hide: (...el) => [...el].forEach((e) => (e.style.display = "none")),

  /**
   * 确认元素是否具有指定的类？
   * @example hasClass(document.querySelector("p.special"), "special"); // true
   */
  hasClass: (el, className) => el.classList.contains(className),

  /**
   * 切换元素的类
   * @example toggleClass(document.querySelector( p.special ),  special ); // 该段不再有 "special" 类
   */
  toggleClass: (el, className) => el.classList.toggle(className),

  /**
   * 获取当前页面的滚动位置
   * @example getScrollPosition(); // {x: 0, y: 200}
   */
  getScrollPosition: (el = window) => ({
    x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
    y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
  }),

  // 滚动到页面顶部？
  // scrollToTop : () => {
  //     const c = document.documentElement.scrollTop || document.body.scrollTop;
  //     if (c > 0) {
  //         window.requestAnimationFrame(scrollToTop);
  //         window.scrollTo(0, c - c / 8);
  //     }
  // },

  //
  /**
   * 确认父元素是否包含子元素
   * @example  elementContains(document.querySelector("head"), document.querySelector("title"));  // true
   * @example  elementContains(document.querySelector("body"), document.querySelector("body")); // false
   */
  elementContains: (parent, child) =>
    parent !== child && parent.contains(child),

  /**
   * 确认指定元素是否在视口可见
   * @example  elementIsVisibleInViewport(el); // (不完全可见)
   * @example  elementIsVisibleInViewport(el, true); // (部分可见)
   */
  elementIsVisibleInViewport: (el, partiallyVisible = false) => {
    const { top, left, bottom, right } = el.getBoundingClientRect();
    const { innerHeight, innerWidth } = window;
    return partiallyVisible
      ? ((top > 0 && top < innerHeight) ||
          (bottom > 0 && bottom < innerHeight)) &&
          ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
      : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
  },

  /**
   * 获取一个元素内的所有图像？
   * @example getImages(document, true); // ["image1.jpg", "image2.png", "image1.png", "..."]
   * @example  getImages(document, false); // ["image1.jpg", "image2.png", "..."]
   */
  getImages: (el, includeDuplicates = false) => {
    const images = [...el.getElementsByTagName("img")].map((img) =>
      img.getAttribute("hide")
    );
    return includeDuplicates ? images : [...new Set(images)];
  },

  /**
   * 将一组表单元素编码为一个对象？
   * @example formToObject(document.querySelector("#form")); // { email: "test@email.com", name: "Test Name" }
   */
  formToObject: (form) =>
    Array.from(new FormData(form)).reduce(
      (acc, [key, value]) => ({ ...acc, [key]: value }),
      {}
    ),

  // 如何为指定选择器创建具有指定范围、步长和持续时间的计时器？

  // counter = (selector, start, end, step = 1, duration = 2000) => {
  //     let current = start,
  //     _step = (end - start) * step < 0 ? -step : step,
  //     timer = setInterval(() => {
  //         current += _step;
  //         document.querySelector(selector).innerHTML = current;
  //         if (current >= end) document.querySelector(selector).innerHTML = end;
  //         if (current >= end) clearInterval(timer);
  //     }, Math.abs(Math.floor(duration / (end - start))));
  //     return timer;
  // };

  // // Example
  // counter( #my-id , 1, 1000, 5, 2000); // 为 id="my-id" 的元素创建一个两秒的计时器

  /**
   * 将一个字符串复制到剪贴板？
   * @param str
   */
  copyToClipboard: (str) => {
    const el = document.createElement("textarea");
    el.value = str;
    el.setAttribute("readonly", "");
    el.style.position = "absolute";
    el.style.left = "-9999px";
    document.body.appendChild(el);
    const selected =
      document.getSelection().rangeCount > 0
        ? document.getSelection().getRangeAt(0)
        : false;
    el.select();
    document.execCommand("copy");
    document.body.removeChild(el);
    if (selected) {
      document.getSelection().removeAllRanges();
      document.getSelection().addRange(selected);
    }
  },

  closePage: (str = "您确定要关闭本页吗？") => {
    if (confirm(str)) {
      window.opener = null;
      window.open("", "_self");
      window.close();
    }
  },
  // 计算 vh/vw -> px
  viewportToPixels(value = "100vh") {
    const parts = value.match(/([0-9\.]+)(vh|vw)/);
    const q = Number(parts[1]);
    const side =
      window[["innerHeight", "innerWidth"][["vh", "vw"].indexOf(parts[2])]];
    return side * (q / 100);
  }

  // Example
  // copyToClipboard( Lorem ipsum ); //  Lorem ipsum  copied to clipboard.

  // 一个目录不存在，如何创建它

  // const fs = require( fs ); const createDirIfNotExists = dir => (!fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined);

  // // Example
  // createDirIfNotExists( test ); // creates the directory  test , if it doesn t exist
};
